import express from 'express';
import { CloudService } from '../services/cloud';

const router = express.Router();
const cloudService = new CloudService();

// 获取云盘文件列表
router.get('/list/:provider', async (req, res) => {
  try {
    const { provider } = req.params;
    const { path = '/', token } = req.query;

    if (!token) {
      return res.status(400).json({ error: 'Access token is required' });
    }

    const files = await cloudService.listFiles(provider, token as string, path as string);
    res.json({ files });
  } catch (error) {
    res.status(500).json({ error: (error as Error).message });
  }
});

// 获取文件下载链接
router.get('/download/:provider', async (req, res) => {
  try {
    const { provider } = req.params;
    const { fileId, token } = req.query;

    if (!fileId || !token) {
      return res.status(400).json({ error: 'File ID and token are required' });
    }

    const downloadUrl = await cloudService.getDownloadUrl(
      provider, 
      token as string, 
      fileId as string
    );
    
    res.json({ downloadUrl });
  } catch (error) {
    res.status(500).json({ error: (error as Error).message });
  }
});

// 搜索云盘文件
router.get('/search/:provider', async (req, res) => {
  try {
    const { provider } = req.params;
    const { keyword, token, path = '/' } = req.query;

    if (!keyword || !token) {
      return res.status(400).json({ error: 'Keyword and token are required' });
    }

    const results = await cloudService.searchFiles(
      provider, 
      token as string, 
      keyword as string, 
      path as string
    );
    
    res.json({ results });
  } catch (error) {
    res.status(500).json({ error: (error as Error).message });
  }
});

// 获取用户信息
router.get('/user/:provider', async (req, res) => {
  try {
    const { provider } = req.params;
    const { token } = req.query;

    if (!token) {
      return res.status(400).json({ error: 'Access token is required' });
    }

    const userInfo = await cloudService.getUserInfo(provider, token as string);
    res.json(userInfo);
  } catch (error) {
    res.status(500).json({ error: (error as Error).message });
  }
});

export { router as cloudRoutes };
